
import javax.swing.table.*;
import java.util.*;
import java.awt.Point;

/**
  * This class implements a sparse-matrix storage model for the table.
  * This allows us to support a large number of rows and columns,
  * without needing to pay the cost for all the cells unless they are used.
  * We choose this model for our spreadsheet because spreadsheet data is
  * often sparse in nature.
  *
  * @see javax.swing.JTable
  * @see javax.swing.table.AbstractTableModel
  * @see SpreadsheetDocument
  * @author Steve Wilson
  */
public class SpreadsheetModel extends AbstractTableModel {
   public static int DEFAULT_ROW_COUNT = 1024;
   public static int DEFAULT_COLUMN_COUNT = 1024;

   private Map sparseMatrix = new HashMap();
   private int maxRow = 0;
   private int maxColumn = 0;

   private Point tmpIndex = new Point(0,0);

   public int getRowCount() {
      return DEFAULT_ROW_COUNT;
   }

   public int getColumnCount() {
      return DEFAULT_COLUMN_COUNT;
   }

   public Object getValueAt(int row, int column) {

      tmpIndex.y = row;
      tmpIndex.x = column;
      Object returnVal = sparseMatrix.get(tmpIndex);
      if (returnVal != null) {
         return returnVal;
      } else {
         return "";
      }
   }

   public void setValueAt(Object val, int row, int column) {
      if (val == null) {
         sparseMatrix.remove(new Point(column, row));
         return;
      }
      maxRow = Math.max(row, maxRow);
      maxColumn = Math.max(column, maxColumn);
      sparseMatrix.put(new Point(column, row), val);
   }


   public boolean isCellEditable( int row, int column ) {
      return true;
   }

   public int getMaxRow() {
      return maxRow;
   }

   public int getMaxColumn() {
      return maxColumn;
   }
}
